const fs = require('fs');
const path = require('path');

// 检查ArkTS文件的基本语法问题
function checkArkTSFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  const issues = [];
  
  // 检查导入路径
  const importRegex = /import\s+.*from\s+['"]([^'"]+)['"]/g;
  let match;
  while ((match = importRegex.exec(content)) !== null) {
    const importPath = match[1];
    if (importPath.startsWith('../') || importPath.startsWith('./')) {
      // 检查相对路径是否存在对应文件
      const resolvedPath = path.resolve(path.dirname(filePath), importPath);
      const possibleExtensions = ['.ets', '.ts', '.js'];
      let found = false;
      
      for (const ext of possibleExtensions) {
        if (fs.existsSync(resolvedPath + ext)) {
          found = true;
          break;
        }
      }
      
      if (!found && !fs.existsSync(resolvedPath)) {
        issues.push(`导入路径可能不存在: ${importPath}`);
      }
    }
  }
  
  // 检查throw语句
  const throwRegex = /throw\s+([^;]+);/g;
  while ((match = throwRegex.exec(content)) !== null) {
    const throwValue = match[1].trim();
    if (!throwValue.startsWith('new Error(') && !throwValue.startsWith('Error(')) {
      issues.push(`throw语句应该抛出Error对象: ${throwValue}`);
    }
  }
  
  // 检查any/unknown类型
  if (content.includes(': any') || content.includes(': unknown')) {
    issues.push('发现any或unknown类型使用');
  }
  
  return issues;
}

// 检查主要文件
const filesToCheck = [
  'entry/src/main/ets/database/DatabaseManager.ets',
  'entry/src/main/ets/database/VehicleDao.ets',
  'entry/src/main/ets/model/VehicleModel.ets',
  'entry/src/main/ets/pages/CarDetail.ets',
  'entry/src/main/ets/pages/Index.ets'
];

console.log('=== ArkTS 语法检查结果 ===\n');

let totalIssues = 0;
for (const file of filesToCheck) {
  const fullPath = path.join(__dirname, file);
  if (fs.existsSync(fullPath)) {
    const issues = checkArkTSFile(fullPath);
    console.log(`📁 ${file}:`);
    if (issues.length === 0) {
      console.log('  ✅ 未发现语法问题');
    } else {
      issues.forEach(issue => {
        console.log(`  ❌ ${issue}`);
      });
      totalIssues += issues.length;
    }
    console.log('');
  } else {
    console.log(`📁 ${file}: 文件不存在\n`);
  }
}

console.log(`=== 检查完成 ===`);
console.log(`总计发现 ${totalIssues} 个潜在问题`);

if (totalIssues === 0) {
  console.log('🎉 所有检查的文件都没有发现明显的语法问题！');
} else {
  console.log('⚠️  仍有一些问题需要注意，但主要的编译错误应该已经修复。');
}